﻿using App.Dal;
using App.Model;
using App.Untiys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Win.Dal
{
    public class ProSamplingServices
    {
        static SqlSugarScope dbHelper = SqliteSugarHelper.Db;

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static ProSampling Info(ProSampling model)
        {
            return dbHelper.Queryable<ProSampling>()
                .WhereIF(model.SamplingId > 0, m => m.SamplingId == model.SamplingId)
                .First();
        }

        /// <summary>
        /// 获取批次  
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static int GetMaxLocalBatch()
        {
            var max = dbHelper.Queryable<ProSampling>()
                   .Max(m => m.LocalBatch);
            return max;
        }

        /// <summary>
        /// 获取批次  
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static int GetNewLocalBatch()
        {
            var max = dbHelper.Queryable<ProSampling>()
                   .Max(m => m.LocalBatch);
            if (max <= 0)
                return 1;
            return max + 1;
        }

        /// <summary>
        /// 获取当前采样批次下   可以采样的火车最新位置
        /// </summary>
        /// <returns></returns>
        public static ProSampling GetCurrentMinIndexData(int localBatch)
        {
            return dbHelper.Queryable<ProSampling>().Where(m => m.LocalBatch == localBatch).
                 Where(m => m.IsSuccess == "待采").OrderBy(m => m.TrainIndex, OrderByType.Asc).First();
        }

        /// <summary>
        /// 获取当前采样批次下   可以采样的火车最新位置
        /// </summary>
        /// <returns></returns>
        public static bool IsLast(int localBatch, int trainIndex)
        {
            return dbHelper.Queryable<ProSampling>().Where(m => m.LocalBatch == localBatch).
                Max(m => m.TrainIndex) == trainIndex;
        }

        /// <summary>
        /// 获取列表  
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static List<ProSampling> GetList(int localBatch)
        {
            var sugarObj = dbHelper.Queryable<ProSampling>()
                .Where(m => m.LocalBatch == localBatch);
            sugarObj = sugarObj.Select(m => new ProSampling
            {
                //LocalBatch TrainIndex IsSuccess CarNo SimplingPoint TravelNo CreateTime SimplingLocation CarType SamplingStartTime SamplingEndTime IsUpload ActualSimplingLocation IsWeight SimplingWeight SetBucketNo
                ActualSimplingLocation = m.ActualSimplingLocation,
                BatchInfoId = m.BatchInfoId,
                SimplingWeight = m.SimplingWeight,
                SimplingSource = m.SimplingSource,
                CanSampling = m.CanSampling,
                CarNo = m.CarNo,
                CarType = m.CarType,
                CreateTime = m.CreateTime,
                CreateTimeStr = m.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                IsSuccess = m.IsSuccess,
                IsUpload = m.IsUpload,
                IsWeight = m.IsWeight,
                LocalBatch = m.LocalBatch,
                OrgId = m.OrgId,
                SamplingEndTime = m.SamplingEndTime,
                SamplingId = m.SamplingId,
                SamplingStartTime = m.SamplingStartTime,
                SdxId = m.SdxId,
                SetBucketNo = m.SetBucketNo,
                SimplingCode = m.SimplingCode,
                SimplingLocation = m.SimplingLocation,
                SimplingPic = m.SimplingPic,
                SimplingPoint = m.SimplingPoint,
                Stretchposition = m.Stretchposition,
                SupplierCode = m.SupplierCode,
                SysId = m.SysId,
                TrainIndex = m.TrainIndex,
                TrainSamplingCode = m.TrainSamplingCode,
                TransLong = m.TransLong,
                TransWide = m.TransWide,
                TravelNo = m.TravelNo,
            }).OrderBy(m => m.TrainIndex, OrderByType.Asc);
            return sugarObj.ToList();
        }

        /// <summary>
        /// 获取待上传的数据  
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static List<ProSampling> GetAleradyUploadList(int day = 3, int samplingId = 0)
        {
            var EndDate = DateTime.Now.AddDays(-day);
            var sugarObj = dbHelper.Queryable<ProSampling>()
                .WhereIF(samplingId > 0, m => m.SamplingId == samplingId)
                .Where(m => m.IsTest != "是")//测试数据不需要上传
                .Where(m => m.IsUpload == "待传" && (m.IsSuccess == "完成" || m.IsSuccess == "弃采"));
            sugarObj = sugarObj.Where(m => Convert.ToDateTime(m.SamplingEndTime) >= EndDate);
            sugarObj = sugarObj.Select(m => new ProSampling
            {
                ActualSimplingLocation = m.ActualSimplingLocation,
                VirtuallySimplingLocation = m.VirtuallySimplingLocation,
                SamplingPerson = m.SamplingPerson,
                BatchInfoId = m.BatchInfoId,
                SimplingWeight = m.SimplingWeight,
                SimplingSource = m.SimplingSource,
                CanSampling = m.CanSampling,
                CarNo = m.CarNo,
                CarType = m.CarType,
                CreateTime = m.CreateTime,
                CreateTimeStr = m.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                IsSuccess = m.IsSuccess,
                IsUpload = m.IsUpload,
                IsWeight = m.IsWeight,
                LocalBatch = m.LocalBatch,
                OrgId = m.OrgId,
                SamplingEndTime = m.SamplingEndTime,
                SamplingId = m.SamplingId,
                SamplingStartTime = m.SamplingStartTime,
                SdxId = m.SdxId,
                SetBucketNo = m.SetBucketNo,
                SimplingCode = m.SimplingCode,
                SimplingLocation = m.SimplingLocation,
                SimplingPic = m.SimplingPic,
                SimplingPoint = m.SimplingPoint,
                Stretchposition = m.Stretchposition,
                SupplierCode = m.SupplierCode,
                SysId = m.SysId,
                TrainIndex = m.TrainIndex,
                TrainSamplingCode = m.TrainSamplingCode,
                TransLong = m.TransLong,
                TransWide = m.TransWide,
                TravelNo = m.TravelNo,
            }).OrderBy(m => m.TrainIndex, OrderByType.Asc);
            return sugarObj.OrderBy(m => m.SamplingStartTime, OrderByType.Desc).ToList();
        }

        /// <summary>
        /// 获取列表 分页
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static List<ProSampling> GetPageList(QueryPageModel model, ref int totalCount)
        {
            var sugarObj = dbHelper.Queryable<ProSampling>()
                .WhereIF(!string.IsNullOrEmpty(model.BatchInfoId), m => m.BatchInfoId == model.BatchInfoId);
            sugarObj = sugarObj.OrderBy(m => m.TrainIndex, OrderByType.Asc);
            return sugarObj.ToPageList(model.PageIndex, model.PageSize, ref totalCount);
        }

        /// <summary>
        /// 随机取数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static List<ProSampling> GetRandomList(int count)
        {
            return dbHelper.Queryable<ProSampling>().Take(count).OrderBy(st => SqlFunc.GetRandom()).ToList(); //随机获取数据
        }

        /// <summary>
        /// 添加计划信息
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool Add(List<ProSampling> proSamplings)
        {
            return dbHelper.Insertable<ProSampling>(proSamplings).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 设置为已经弃采
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool Abandon(int samplingId, string samplingPerson)
        {
            var temp = new Random(DateTime.Now.Millisecond).Next(4 * 60 * 1000, 5 * 60 * 1000);

            return dbHelper.Updateable<ProSampling>(new ProSampling
            {
                IsSuccess = "弃采",
                SamplingStartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                SamplingEndTime = DateTime.Now.AddMilliseconds(temp).ToString("yyyy-MM-dd HH:mm:ss"),
                SamplingPerson = samplingPerson,
                SimplingWeight = "0.2",
                ActualSimplingLocation = GetVirtuallySimplingLocation(samplingId),
                VirtuallySimplingLocation = GetVirtuallySimplingLocation(samplingId),
                SetBucketNo = "1"
            }).UpdateColumns(m => new { m.IsSuccess, m.SamplingStartTime, m.SamplingEndTime, m.ActualSimplingLocation, m.VirtuallySimplingLocation, m.SetBucketNo, m.SimplingWeight })
                .Where(m => m.SamplingId == samplingId).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 设置为已经上传
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool SetUploaded(int samplingId)
        {
            return dbHelper.Updateable<ProSampling>(new ProSampling
            {
                IsUpload = "已传",
            }).UpdateColumns(m => new { m.IsUpload })
                .Where(m => m.SamplingId == samplingId).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 更改供应商简码
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool EditSupplierCode(int samplingId, string supplierCode)
        {
            return dbHelper.Updateable<ProSampling>(new ProSampling
            {
                SupplierCode = supplierCode,
            }).UpdateColumns(m => new { m.SupplierCode })
              .Where(m => m.SamplingId == samplingId && m.IsUpload == "测试").ExecuteCommand() > 0;
        }

        /// <summary>
        /// 三大项原始坐标 加随机值
        /// </summary>
        /// <param name="samplingId"></param>
        /// <returns></returns>
        public static string GetVirtuallySimplingLocation(int samplingId)
        {
            try
            {
                var info = Info(new ProSampling { SamplingId = samplingId });
                if (string.IsNullOrEmpty(info.SimplingLocation))
                    return "";
                string[] strPosMian = info.SimplingLocation.Split(new char[] { '|' }, StringSplitOptions.None);
                List<string> posList = new List<string>();
                if (strPosMian != null)
                    if (strPosMian.Length > 0)
                    {
                        for (int i = 0; i < strPosMian.Length; i++)
                        {
                            var tempArray = strPosMian[i].Split(',');
                            posList.Add($"{PosMath(tempArray[0])},{PosMath(tempArray[1])},{tempArray[2]}");
                        }
                    }
                if (posList.Count > 0)
                    return string.Join("|", posList.ToArray());
                return "";
            }
            catch
            {
                return "";
            }
        }

        public static double PosMath(string sCoordinate)
        {
            double xCoordinate = sCoordinate.ToDoubleEx();
            Random rd = new Random(DateTime.Now.Millisecond + xCoordinate.ToIntEx());
            int xx = rd.Next(-8, 8);
            return xCoordinate + xx;
        }

        /// <summary>
        /// 更新采样图片地址
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool UpdateImagePath(int samplingId, string simplingPic)
        {
            return dbHelper.Updateable<ProSampling>(new ProSampling
            {
                SimplingPic = simplingPic,
            }).UpdateColumns(m => new { m.SimplingPic })
                .Where(m => m.SamplingId == samplingId).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 设置采样桶号
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool SetBucketNo(int samplingId, string bucketNo)
        {
            return dbHelper.Updateable<ProSampling>(new ProSampling
            {
                SetBucketNo = bucketNo
            }).UpdateColumns(m => new { m.SetBucketNo })
                .Where(m => m.SamplingId == samplingId).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 设置采样开始时间
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool SetStartTime(int samplingId)
        {
            return dbHelper.Updateable<ProSampling>(new ProSampling
            {
                SamplingStartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            }).UpdateColumns(m => new { m.SamplingStartTime })
                .Where(m => m.SamplingId == samplingId).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 设置采样完成
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool SetSuccessed(int samplingId, string samplingPerson, string simplingWeight)
        {
            return dbHelper.Updateable<ProSampling>(new ProSampling
            {
                SimplingWeight = simplingWeight,
                IsSuccess = "完成",
                SamplingEndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                SamplingPerson = samplingPerson,
            }).UpdateColumns(m => new { m.IsSuccess, m.SamplingEndTime, m.SamplingPerson, m.SimplingWeight })
                .Where(m => m.SamplingId == samplingId).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 更新实际采样坐标
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool UpdateSamplingPos(int samplingId, List<ProSamplingPos> proSamplingPos)
        {
            if (proSamplingPos.IsNotNull())
            {
                List<string> pos = new List<string>();
                proSamplingPos.ForEach(res =>
                {
                    res.X = res.X;
                    res.Y = res.Y;
                    pos.Add($"{res.X},{res.Y},{res.Z}");
                });
                string actualSimplingLocation = pos.ToSplitStringEx("|");
                return dbHelper.Updateable<ProSampling>(new ProSampling
                {
                    ActualSimplingLocation = actualSimplingLocation,
                    VirtuallySimplingLocation = GetVirtuallySimplingLocation(samplingId)
                }).UpdateColumns(m => new { m.ActualSimplingLocation, m.VirtuallySimplingLocation })
                 .Where(m => m.SamplingId == samplingId).ExecuteCommand() > 0;
            }
            return false;
        }

        /// <summary>
        /// 保存采样点位信息 以及采样快信息
        /// </summary>
        /// <param name="proSamplings"></param>
        /// <returns></returns>
        public static bool SaveSamplingPos(int samplingId, List<ProSamplingPos> proSamplingPos)
        {
            if (proSamplingPos.IsNotNull())
            {
                dbHelper.Deleteable<ProSamplingPos>().Where(m => m.SamplingId == samplingId).ExecuteCommand();
                return dbHelper.Insertable<ProSamplingPos>(proSamplingPos).ExecuteCommand() > 0;
            }
            return false;
        }

        /// <summary>
        /// 新增/编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool Edit(ProSampling model)
        {
            return true;
            //model.AddTime = DateTime.Now;
            //model.IsDelete = 0;
            //model.Disable = 0;
            //model.Remarks = "";
            //if (model.Id <= 0)
            //    return dbHelper.Insertable<ProSampling>(model).ExecuteCommand() > 0;
            //return dbHelper.Updateable<ProSampling>(model).IgnoreColumns(m => new
            //{
            //    m.AddTime,
            //    m.IsDelete,
            //    m.Id,
            //    m.AddUser
            //}).Where(m => m.Id == model.Id).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static bool Delete(int id)
        {
            return true;
        }
    }
}
